package tool

import (
	"gorm.io/gorm"
	"math"
)

// 分页组件
// 除gorm其他类型均为非指针类型
// currentPage - 当前页  perPageSize - 每页大小 param 查询的结构体
// param传地址
func Page(currentPage, perPageSize int, db *gorm.DB, paramAddr any) (*dataPage, error) {
	var offset, limit int
	if currentPage <= 1 {
		currentPage = 1
	}
	if perPageSize <= 0 {
		perPageSize = 10
	}
	offset = (currentPage - 1) * perPageSize
	limit = perPageSize

	var count int64
	err := db.Count(&count).Offset(offset).Limit(limit).
		Find(paramAddr).Error
	if err != nil {
		return nil, err
	}

	pageNum := int(math.Ceil(float64(count) / float64(perPageSize)))
	result := dataPage{
		Data:        paramAddr,
		CurrentPage: currentPage,
		PerPageSize: perPageSize,
		Total:       count,
		PageNum:     pageNum,
		HasPrx: func() bool {
			if currentPage == 1 {
				return false
			}
			return true
		}(),
		HasNext: func() bool {
			if currentPage == pageNum {
				return false
			}
			return true
		}(),
	}
	return &result, nil
}

type dataPage struct {
	Data        any   `json:"result"`
	CurrentPage int   `json:"current_page"`
	PerPageSize int   `json:"per_page_size"`
	Total       int64 `json:"total"`
	PageNum     int   `json:"page_num"`
	HasPrx      bool  `json:"has_prx"`
	HasNext     bool  `json:"has_next"`
}
